package com.kidfruit.controller;

import com.kidfruit.model.TUser;
import com.kidfruit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userRest")
public class UserRestController {
    @Autowired
    UserService userService;  //Service which will do all data retrieval/manipulation work


    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<List<TUser>> listAllUsers() {
        List<TUser> users = userService.getAllUsers();
        if (users.isEmpty()) {
            return new ResponseEntity<List<TUser>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<TUser>>(users, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public TUser getUser(@PathVariable int id) {
        TUser user = userService.getUserById(id);
        return user;
    }

    @RequestMapping(value = "/user/", method = RequestMethod.PUT)
    public String updateUser(@RequestBody TUser user) {
        TUser currentUser = userService.getUserById(user.getId());
        if (currentUser != null) {
            int result = userService.updateUser(user);
            return "更新成功" + Integer.toString(result);
        }
        return "不存在该用户";
    }

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public String addUser(@RequestBody TUser user) {
        TUser currentUser = userService.getUserById(user.getId());
        if (currentUser == null) {
            int result = userService.addUser(user);
            return "增加成功" + Integer.toString(result);
        }
        return "用户已存在";
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public String addUser(@PathVariable int id) {
        int result = userService.deleteUserById(id);
        return "删除结果"+Integer.toString(result);
    }
}
